package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.OrdersParticularsMapper;
import com.guigu.pojo.*;
import com.guigu.service.*;
import com.guigu.service.utils.MyIdAdd;
import org.apache.ibatis.jdbc.RuntimeSqlException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersParticularsServiceImpl extends ServiceImpl<OrdersParticularsMapper, OrdersParticulars> implements OrdersParticularsService {

    @Autowired
    ShopInfoService shopInfoService;
    @Autowired
    OrdersService ordersService;
    @Autowired
    UsersService usersService;
    @Autowired
    ReturnShopInfoService returnShopInfoService;
    @Autowired
    CompanyRunningWaterService waterService; //流水账户
    @Autowired
    MyIdAdd myIdAdd;//编号工具

    //根据订单详情查询商品
    @Override
    public Page<OrdersParticulars> queryOrdersParticulars(OrdersParticulars ordersParticulars, Integer pageno, Integer pagesize) {

        QueryWrapper queryWrapper = new QueryWrapper();
        //拿到父id查询详情表
        queryWrapper.eq("p_id", ordersParticulars.getPId());

        Page<OrdersParticulars> page = this.page(new Page<OrdersParticulars>(pageno, pagesize), queryWrapper);
        //循环给值
        for (OrdersParticulars particulars : page.getRecords()) {
            particulars.setShopInfo(shopInfoService.queryShopById(particulars.getGId()));

        }


        return page;
    }

    @Override
    public Page<OrdersParticulars> queryOrdersParticularsreturn(Integer loginUserId, OrdersParticulars ordersParticulars, Integer pageno, Integer pagesize) {
        QueryWrapper queryWrapperXQ = new QueryWrapper();
        queryWrapperXQ.eq("is_return", "1");

        Page<OrdersParticulars> page = this.page(new Page<OrdersParticulars>(pageno, pagesize), queryWrapperXQ);
        for (OrdersParticulars particulars : page.getRecords()) {
            //根据订单详情的父id，查询订单表的订单对象
            QueryWrapper o = new QueryWrapper();
            if (particulars.getPId() != null) {
                o.eq("id", particulars.getPId());
            }

            o.eq("comm_id", loginUserId);
            Orders orders = ordersService.getOne(o);
            //根据订单对象的用户id，查询用户表的用户对象
            orders.setUsers(usersService.getById(orders.getUId()));
            //将组装好的订单对象存入属性内
            particulars.setOrders(orders);

            QueryWrapper<ReturnShopInfo> q = new QueryWrapper();
            //根据详情表的id和审核是否通过来当条件查询
            q.eq("od_id", particulars.getId());
            q.eq("is_audit", "1");
            q.eq("Is_delete", "0");
            System.out.println("========" + returnShopInfoService.getOne(q));
            particulars.setReturnShopInfo(returnShopInfoService.getOne(q));
        }

        return page;
    }

    //根据订单id查详情
    @Override
    public List<OrdersParticulars> queryDetailByOid(Integer id) {
        QueryWrapper<OrdersParticulars> queryWrapper =
                new QueryWrapper<OrdersParticulars>();
        queryWrapper.eq("p_id", id);
        List<OrdersParticulars> list = this.list(queryWrapper);
        for (OrdersParticulars obj : list) {
            obj.setShopInfo(shopInfoService.queryShopById(obj.getGId()));
        }
        return list;
    }


    @Override
    public List<OrdersParticulars> queryParticulars(Integer id) {
        QueryWrapper<OrdersParticulars> queryWrapper = new QueryWrapper<OrdersParticulars>();
        queryWrapper.eq("p_id", id);
        return this.list(queryWrapper);
    }

    //根据id查询订单详情对象
    @Override
    public OrdersParticulars queryDeatilById(Integer id) {

        OrdersParticulars detail = this.getById(id);
        if (detail != null) {
            //查询订单 如果是 g1 g2 g3 g4 退货状态都是未收到货
            //如果是 g5 g6 退货状态都是已收到货
            detail.setOrders(ordersService.queryOrderById(detail.getPId()));
            detail.setShopInfo(shopInfoService.queryShopById(detail.getGId()));
        }
        return detail;
    }

    //未出货可直接退款
    @Transactional
    @Override
    public Map returnMoneyById(OrdersParticulars detail) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "退款失败");
        OrdersParticulars op = this.getById(detail.getId());
        if (op != null) {
            op.setIsReturn(2);
            this.updateById(op);//设置为退货完成
            Orders order = ordersService.getById(op.getPId());
            //添加流水记录
            CompanyRunningWater water = new CompanyRunningWater();
            water.setPipelineId(myIdAdd.idadd("500", true));
            water.setAccountId(10); //总台账户
            water.setUid(order.getUId()); //退款用户
            water.setOid(op.getId().toString()); //订单详情id
            water.setRmoney(op.getSumPrice()); //退款金额
            water.setRdate(new Date()); //退款时间
            water.setRtype(2); //订单退款
            water.setIsDelete(0);
            boolean b1 = waterService.save(water);
            //公司账户扣钱
            Users account = usersService.getById(10);
            account.setBalance(account.getBalance() - op.getSumPrice());
            boolean b2 = usersService.updateById(account);
            //用户收钱
            Users user = usersService.getById(order.getUId());
            user.setBalance(user.getBalance() + op.getSumPrice());
            boolean b3 = usersService.updateById(user);
            if (b1 && b2 && b3) {
                map.put("code",1);
                map.put("msg","退款成功");
            }else {
                throw new RuntimeException();
            }
            //查询是否还有详情
            QueryWrapper<OrdersParticulars> queryWrapper =
                    new QueryWrapper<OrdersParticulars>();
            queryWrapper.eq("p_id", op.getPId());
            List<OrdersParticulars> list = this.list(queryWrapper);
            int num = 0;
            for (OrdersParticulars ordersParticulars : list) {
                if (ordersParticulars.getIsReturn() == 2) {
                    num++;
                }
            }
            if (list.size() == num) {
                //如果全部取消退款修改订单为全部退货
                order.setOrderState("o-4");
                order.setGoodsState("g-10");
                ordersService.updateById(order);
            }
        }
        return map;
    }

    //退款前查询订单详情和订单信息
    @Override
    public Map queryDeatilById2(Integer id) {
        Map map=new HashMap();
        OrdersParticulars detail = this.getById(id);
        if (detail != null) {
            //查询订单 如果是 g1 g2 g3 g4 退货状态都是未收到货
            //如果是 g5 g6 退货状态都是已收到货
            Orders order = ordersService.queryOrderById(detail.getPId());
            detail.setOrders(order);
            if (order.getGoodsState().equals("g-1") ||
                    order.getGoodsState().equals("g-2") ||
                    order.getGoodsState().equals("g-3") ||
                    order.getGoodsState().equals("g-4")
            ){
                map.put("shopState","0");
            }else {
                map.put("shopState","1");
            }
            map.put("detail",detail);
        }
        return map;
    }
}
